package org.example.java8.collector;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 夏焰波
 * @date 2020-07-14 0:34
 */
public class CollectorIntroduce {
    public static void main(String[] args) {
        List<Apple> list = Arrays.asList(new Apple("green", 150)
                , new Apple("yellow", 130)
                , new Apple("green", 200)
                , new Apple("green", 150)
                , new Apple("yellow", 130)
                , new Apple("green", 200));
        //聚合
        List<Apple> greenList = list.stream().filter(a -> a.getColor().equals("green"))
                .collect(Collectors.toList());
        Optional.ofNullable(greenList).ifPresent(System.out::println);

        //分组
        Optional.ofNullable(groupByNormal(list)).ifPresent(System.out::println);
        Optional.ofNullable(groupByFunction(list)).ifPresent(System.out::println);
        Optional.ofNullable(groupByCollector(list)).ifPresent(System.out::println);

    }

    private static Map<String, List<Apple>> groupByNormal(List<Apple> apples) {
        Map<String, List<Apple>> map = new HashMap<>();
        for (Apple a : apples) {
            List<Apple> list = map.get(a.getColor());
            if (null == list) {
                list = new ArrayList<>();
                map.put(a.getColor(), list);
            }
            list.add(a);
        }
        return map;
    }

    private static Map<String, List<Apple>> groupByFunction(List<Apple> apples) {
        //这个map此时是final修饰的，不能对它进行更改
        Map<String, List<Apple>> map = new HashMap<>();
        apples.stream().forEach(a -> {
            List<Apple> colorList = Optional.ofNullable(map.get(a.getColor()))
                    .orElseGet(() -> {
                        List<Apple> list = new ArrayList<>();
                        map.put(a.getColor(), list);
                        return list;
                    });
            colorList.add(a);
        });
        return map;
    }

    private static Map<String, List<Apple>> groupByCollector(List<Apple> apples) {
        return apples.stream().collect(Collectors.groupingBy(Apple::getColor));
    }


}
